package com.service.imp;

import com.common.Base;
import com.common.Result;
import com.entity.Article;
import com.entity.ArticleData;
import com.repository.ArticleRepository;
import com.service.ArticleDataService;
import com.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author：Luohuiyong
 * @Description:
 * @Date: Created in 11:06 2019/1/9
 */
@Service
public class ArticleServiceImp implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private ArticleDataService articleDataService;

    /**
     * 查看文章并更新阅读数
     * @param id
     * @return
     */
    public Article findOne(int id){
        Optional<Article> optionalUser = articleRepository.findById(id);

        ArticleData articleData = new ArticleData();
        articleData.setArticleId(id);
        articleDataService.updateReadNum(articleData);

        return optionalUser.get();
    }

    /**
     * 新增一个实体
     * @param article
     * @return
     */
    @Transactional
    @Override
    public Result create(Article article){
        article.setCreatedAt(new Date());
        Article  article1 = articleRepository.save(article);

        ArticleData articleData = new ArticleData();
        articleData.setArticleId(article1.getId());
        articleData.setCommentNum(0);
        articleData.setLikeNum(0);
        articleData.setReadNum(0);
        articleData.setWords(article.getContent().length());
        articleDataService.create(articleData);

        return Base.success();
    }

    public Result update(Article bean){
        Optional<Article> optionalArticle = articleRepository.findById(bean.getId());
        Article article = optionalArticle.get();
        article.setTitle(bean.getTitle());
        article.setImg(bean.getImg());
        article.setContent(bean.getContent());
        article.setIsPublic(bean.getIsPublic());
        article.setUpdatedAt(new Date());

        articleRepository.save(article);

        return Base.success();
    }

    /**
     * 投稿
     * @param article
     * @return
     */
    @Transactional
    @Override
    public Result submit(Article article){
        if(article.getId() != null && article.getTopicId() != null){
            Optional<Article> optionalArticle = articleRepository.findById(article.getId());
            Article article1 = optionalArticle.get();
            if(article1.getTopicId() == article.getTopicId()){
                return Base.error("已投稿过该专题");
            }
            else {
                articleRepository.updateTopicIdById(article.getId(),article.getTopicId());
            }

        }

        return Base.success();
    }

    /**
     * 分页查询数据
     * @param article
     * @return
     */
    @Override
    public Result index(Article article){

        Pageable pageable = new PageRequest(article.getPage(),article.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Article> page = articleRepository.findAllByIsPublicAndTopicIdIsNotNull(1,pageable);
        long total = articleRepository.countByIsPublicAndTopicIdIsNotNull(1);
        long maxPage = total/article.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }

    /**
     * 根据userId分页查询数据
     * @param article
     * @return
     */
    @Override
    public Result indexByUserId(Article article){

        Pageable pageable = new PageRequest(article.getPage(),article.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Article> page = articleRepository.findAllByUserId(article.getUserId(),pageable);
        long total = articleRepository.countByUserId(article.getUserId());
        long maxPage = total/article.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }

    /**
     * 根据userId分页查询公开文章
     * @param article
     * @return
     */
    @Override
    public Result indexByUserIdAndPublic(Article article){

        Pageable pageable = new PageRequest(article.getPage(),article.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Article> page = articleRepository.findAllByUserIdAndIsPublic(article.getUserId(),1,pageable);
        long total = articleRepository.countByUserIdAndIsPublic(article.getUserId(),1);
        long maxPage = total/article.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }



    /**
     * 根据topicId分页查询数据
     * @param article
     * @return
     */
    @Override
    public Result indexByTopicId(Article article) {
        Pageable pageable = new PageRequest(article.getPage(),article.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Article> page = articleRepository.findAllByTopicId(article.getTopicId(),pageable);
        long total = articleRepository.countByTopicId(article.getTopicId());
        long maxPage = total/article.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }

    /**
     * 推荐文章
     * @return
     */
    @Override
    public Result recommend() {
        List<Article> list = articleRepository.findByIsRecommend(1);
        return Base.success(list);
    }

    @Override
    public Result search(Article article) {
        if(StringUtils.hasText(article.getTitle())){
            Pageable pageable = new PageRequest(article.getPage(),article.getPageSize(),Sort.Direction.DESC,"createdAt");
            String title = "%" + article.getTitle() + "%";
            Page<Article> page = articleRepository.findAllByTitleLike(title,pageable);
            long total = articleRepository.countByTitleLike(title);
            long maxPage = total/article.getPageSize();

            return Base.success(page.getContent(),total,maxPage);
        }
        return null;
    }

    /**
     * 删除文章
     * @param bean
     * @return
     */
    @Transactional
    @Override
    public Result delete(Article bean){
        if(bean.getId() != null){
            articleRepository.deleteById(bean.getId());
        }

        return Base.success();
    }

}
